package top.jianx.storage.utils;

import cn.hutool.core.io.FileUtil;
import cn.hutool.core.util.ArrayUtil;
import org.springframework.util.Assert;

import java.io.File;
import java.util.ArrayList;
import java.util.List;

/**
 * 〈文件工具类〉
 *
 * @since: 1.0.0
 * @author: Jianx
 * @date: 2022/3/20
 */
public class FileUtils extends FileUtil {

    /**
     * 获取文件后缀名
     *
     * @param fullName 文件全名
     * @return {String}
     */
    public static String getFileExtension(String fullName) {
        Assert.notNull(fullName, "file fullName is null.");
        String fileName = new File(fullName).getName();
        int dotIndex = fileName.lastIndexOf('.');
        return (dotIndex == -1) ? "" : fileName.substring(dotIndex + 1);
    }

    /**
     * 获取文件模块
     *
     * @param path 路径
     * @return {String}
     */
    public static String getFileModule(String path) {
        path = path.replaceAll("\\\\", "/");
        String[] split = path.split(":");
        if (split.length == 2) {
            //去掉盘符
            path = split[1];
        }
        return path;
    }

    /**
     * 递归遍历目录
     *
     * @param path 当前遍历目录
     * @return 目录列表
     */
    public static List<String> loopDirectories(String path) {
        return loopDirectories(file(path), new ArrayList<>());
    }

    /**
     * 递归遍历目录
     *
     * @param file 当前遍历目录
     * @return 目录列表
     */
    private static List<String> loopDirectories(File file, List<String> directories) {
        if (null == file) {
            return directories;
        } else if (!file.exists()) {
            return directories;
        }

        if (file.isDirectory()) {
            final File[] subDirectories = file.listFiles(File::isDirectory);
            if (ArrayUtil.isNotEmpty(subDirectories)) {
                for (File tmp : subDirectories) {
                    directories.add(tmp.getAbsolutePath());
                    loopDirectories(tmp, directories);
                }
            }
        }

        return directories;
    }

}

